<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    class="workflow-start-dialog"
  >
    <div class="dialog-content">
      <!-- 表单填写区域 -->
      <div class="form-section">
        <el-card>
          <template #header>
            <div class="form-header">
              <el-icon size="18" color="#409eff">
                <Document />
              </el-icon>
              <span class="form-title">填写申请信息</span>
              <span class="required-tip">* 为必填项</span>
            </div>
          </template>
          
          <!-- 紧急程度选择 -->
          <div class="priority-section">
            <el-form 
              :model="priorityForm" 
              label-width="120px" 
              size="large"
            >
              <el-form-item label="紧急程度" required>
                <el-select 
                  v-model="priority" 
                  placeholder="请选择紧急程度"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="低" :value="-1" />
                  <el-option label="普通" :value="0" />
                  <el-option label="紧急" :value="1" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 使用FormPreview组件渲染动态表单 -->
          <div class="form-content">
            <FormPreview
              v-if="formFields.length > 0"
              ref="formPreviewRef"
              :fields="formFields"
              @form-data-change="handleFormDataChange"
            />
            
            <!-- 无表单字段时的提示 -->
            <div v-else class="no-form-tip">
              <el-empty description="该工作流暂无需要填写的表单" />
            </div>
          </div>
        </el-card>
      </div>

      <!-- 提交说明 -->
      <div class="submit-note">
        <el-alert
          title="提交说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>提交后将进入工作流审批流程，请确保填写信息准确无误。</p>
            <p>您可以在"我的申请"中查看申请进度和处理结果。</p>
          </template>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitting"
          :disabled="!canSubmit"
        >
          {{ submitting ? '提交中...' : '提交申请' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document
} from '@element-plus/icons-vue'
import FormPreview from '/@/components/FormDesigner/FormPreview.vue'
import type { WorkflowConfiguration } from '../types'
import type { FormField } from '/@/components/FormDesigner/types'
import { startWorkflowInstance } from '/@/api/workflow'

interface Props {
  visible: boolean
  workflow: WorkflowConfiguration | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 组件引用
const formPreviewRef = ref()

// 响应式数据
const submitting = ref(false)
const formData = ref<Record<string, any>>({})
const priority = ref<number>(0) // 紧急程度，默认为普通
const priorityForm = ref({ priority: 0 }) // 紧急程度表单数据

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 弹窗标题
const dialogTitle = computed(() => {
  return `启动工作流 - ${props.workflow?.basicInfo?.name || ''}`
})

// 表单字段
const formFields = computed<FormField[]>(() => {
  return props.workflow?.formConfig?.fields || []
})

// 是否可以提交
const canSubmit = computed(() => {
  // 紧急程度必须选择
  if (priority.value === undefined || priority.value === null) {
    return false
  }
  
  if (formFields.value.length === 0) {
    return true // 无表单字段时可以直接提交
  }
  
  // 检查必填字段是否都已填写
  const requiredFields = formFields.value.filter(field => field.required)
  return requiredFields.every(field => {
    const value = formData.value[field.name]
    if (Array.isArray(value)) {
      return value.length > 0
    }
    return value !== undefined && value !== null && value !== ''
  })
})

// 方法
const handleFormDataChange = (data: Record<string, any>) => {
  formData.value = { ...data }
}

const handleSubmit = async () => {
  if (!props.workflow) {
    ElMessage.error('工作流信息不完整')
    return
  }

  // 如果有表单，先验证表单
  if (formFields.value.length > 0 && formPreviewRef.value) {
    try {
      const isValid = await formPreviewRef.value.validate()
      if (!isValid) {
        ElMessage.warning('请检查表单填写是否正确')
        return
      }
    } catch (error) {
      ElMessage.warning('请完善表单信息')
      return
    }
  }

  // 确认提交
  try {
    await ElMessageBox.confirm(
      '确定要提交该申请吗？提交后将进入审批流程。',
      '确认提交',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return // 用户取消
  }

  submitting.value = true
  
  try {
    const submitData = {
      workflowId: props.workflow.id,
      workflowName: props.workflow.basicInfo.name,
      variables: formData.value,
      priority: priority.value,
    }
    
    const response = await startWorkflowInstance(submitData)
    
    ElMessage.success('申请提交成功')
    emit('success', response.data)
  } catch (error) {
    ElMessage.error('提交失败，请重试')
    console.error('提交工作流失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  // 检查是否有未保存的数据
  if (Object.keys(formData.value).length > 0) {
    ElMessageBox.confirm(
      '当前有未提交的数据，确定要关闭吗？',
      '确认关闭',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      dialogVisible.value = false
    }).catch(() => {
      // 用户取消关闭
    })
  } else {
    dialogVisible.value = false
  }
}

// 监听弹窗打开，重置表单数据
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      formData.value = {}
      priority.value = 0 // 重置紧急程度为普通
      // 等待组件渲染完成后初始化表单
      nextTick(() => {
        if (formPreviewRef.value && formPreviewRef.value.resetForm) {
          formPreviewRef.value.resetForm()
        }
      })
    }
  }
)
</script>

<style scoped>
.workflow-start-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh;
    margin-bottom: 5vh;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-dialog__header) {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
    flex: 1;
    overflow: auto;
  }
  
  :deep(.el-dialog__footer) {
    padding: 16px 24px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.dialog-content {
  padding: 20px 24px;
}

.form-section {
  margin-bottom: 20px;
}

.form-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.required-tip {
  color: #f56c6c;
  font-size: 12px;
}

.priority-section {
  padding: 16px;
  margin-bottom: 16px;
}

.priority-section :deep(.el-form-item) {
  margin-bottom: 0;
}

.form-content {
  min-height: 200px;
}

.no-form-tip {
  padding: 40px 20px;
  text-align: center;
}

.submit-note {
  margin-bottom: 0;
}

.submit-note :deep(.el-alert__content) {
  line-height: 1.6;
}

.submit-note p {
  margin: 4px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .workflow-start-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 2.5vh auto;
    }
  }
  
  .dialog-content {
    padding: 16px;
  }
}
</style>